package com.airnewslinkosky.ticket.net;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Log;

import com.airnewslinkosky.ticket.util.Constants;

public class HttpUtils {

	private static final String tag = HttpUtils.class.getSimpleName();
	private static final String exceptionResult = "{\"errorcode\":\"-1\",\"msg\":\"系统繁忙，请稍后重试!\"}";
	
	
	/**
	 * POST请求
	 * @param mContext
	 * @param url
	 * @param paramsMap
	 * @return
	 */
	public static String doPost(Context mContext, String url, HashMap<String, String> paramsMap){
		AndroidHttpClient client = AndroidHttpClient.newInstance(mContext, Constants.USER_AGENT);
		HttpPost request = null;
		InputStream entityStream = null;
		String result = null;
		try {
			request = new HttpPost(url);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			for (Map.Entry<String, String> m : paramsMap.entrySet()) {
				params.add(new BasicNameValuePair(m.getKey(), m.getValue()));
			}
			request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			Log.d(tag, "request-url=="+url + (params != null ? params.toString() : null));
			HttpResponse response = client.execute(request);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				entityStream = response.getEntity().getContent();
				result = convertStreamToString(entityStream);
			}
		} catch (Exception e) {
			request.abort();
			e.printStackTrace();
		} finally {
			closeStream(entityStream);
			closeClient(client);
		}
		if(TextUtils.isEmpty(result)){
			result = exceptionResult;
		}
		Log.d(tag, "result=="+result);
		return result;
	}
	
	
	/**
	 * 请求图片
	 * @param mContext
	 * @param url
	 * @return
	 */
	public static Bitmap getBitmapFromUrl(Context mContext, String url){
		AndroidHttpClient client = AndroidHttpClient.newInstance(mContext, Constants.USER_AGENT);
		HttpGet request = null;
		InputStream ins = null;
		try {
			request = new HttpGet(url);
			HttpResponse response = client.execute(request);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				ins = response.getEntity().getContent();
				return BitmapFactory.decodeStream(ins);
			}
		} catch (Exception e) {
			request.abort();
			e.printStackTrace();
			return null;
		} finally {
			closeStream(ins);
			closeClient(client);
		}
		return null;
	}
	
	
	/**
	 * 下载文件
	 * @param context
	 * @param url
	 * @param file
	 * @param callback
	 * @return
	 */
	public static boolean downloadFile(Context context, String url, File file, DownloadCallback callback){
		DataInputStream in = null;
		DataOutputStream out = null;
		int downloadSize = 0;
		boolean isCancelled = false;
		boolean isSccuess = false;
		AndroidHttpClient client = AndroidHttpClient.newInstance(context, Constants.USER_AGENT);
		try {
			HttpGet request = null;
			request = new HttpGet(url);
			HttpResponse response = client.execute(request);
			Header contentLength = response.getFirstHeader("Content-Length");
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				in = new DataInputStream(response.getEntity().getContent());
			}
			int total = Integer.parseInt(TextUtils.isEmpty(contentLength.getValue()) ? "0" : contentLength.getValue());
			out = new DataOutputStream(new FileOutputStream(file));//使用MODE_WORLD_READABLE才能正常安装
			byte[] buffer = new byte[1024];
			int count = 0;
			int loopCount = 0;//循环次数
			while (!isCancelled && (count = in.read(buffer)) > 0) {
				out.write(buffer, 0, count);
				downloadSize += count;
				int progress = (int)(downloadSize*100/total);
				if(++loopCount%20 == 0 || progress == 100){
					if(callback != null){
						isCancelled = callback.onProgressChanged(progress, downloadSize, total);
					}
				}
			}
			if(downloadSize == total){//下载成功
				if(callback != null){
					callback.onProgressChanged(100, downloadSize, total);
				}
				isSccuess = true;
				Log.i(tag, "====================download sccuess");
			}
			if(isCancelled){
				file.delete();
				Log.i(tag, "====================download isCancelled= "+isCancelled);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			closeStream(out);
			closeStream(in);
			closeClient(client);
		}
		return isSccuess;
	}


	private static void closeClient(AndroidHttpClient client) {
		if (client != null) {
			client.close();
			client = null;
		}
	}
	
	
	private static String convertStreamToString(InputStream is) {
		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "UTF-8"), 8 * 1024);
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			sb.delete(0, sb.length());
		} finally {
			closeStream(is);
		}
		return sb.toString();
	}
	
	
	private static void closeStream(Closeable stream) {
		if (stream != null) {
			try {
				stream.close();
			} catch (IOException e) {
			}
		}
	}
}
